import { Breadcrumb, message } from 'antd';
import React, { FC, useState } from 'react';
import {
  FormPanel,
  type FormPanelObject,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
  InputType,
  ExtendReader,
  Utils,
} from 'lfun-bg-comp';
import { useNavigate } from 'react-router-dom';
import _ from 'lodash';
import { PageContainer } from '@/component/page-container';
import { GENDER } from '@/constant/basicOptions';
import { ID_TYPE } from '@/constant/studentOptions';
import { POSITION_TYPE } from '@/constant/teachOptions';
import { TransferIn, createTransferIn, getTransferTeacher } from '@/service/teacher/transfer';
import { getProvinceCityCascader, searchSchoolByKeyOptions } from '@/service/options';
import utils from '@/utils';
import useCountry from '@/hooks/useCountry';

const Groups: FC = () => {
  const navigate = useNavigate();
  const [values, setValues] = useState<any>();
  const [nonSys, setNonSys] = useState<boolean>(false);
  const [submitForm, setSubmitForm] = useState<FormPanelObject>();
  const country = useCountry();
  const list = [
    {
      title: '教师查询',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '姓名',
          name: 'teacher_name',
          key: 'teacher_name',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '证件类型',
          name: 'teacher_id_type',
          key: 'teacher_id_type',
          relationFields: ['teacher_id_number'],
          required: true,
          inputType: InputType.select,
          renderOption: ID_TYPE,
        },
        {
          label: '证件号码',
          name: 'teacher_id_number',
          key: 'teacher_id_number',
          required: true,
          textRange: [0, 30],
          ruleType: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type === 'resident_id_card') {
              return 'cnPeopleNo';
            }
            return '';
          },
        },
      ],
    },
  ];

  const checkInfoList = [
    {
      title: '教师基本信息',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      inputs: [
        {
          label: '姓名',
          name: 'add_teacher.teacher_name',
          key: 'add_teacher.teacher_name',
          required: true,
        },
        {
          label: '证件类型',
          name: 'add_teacher.teacher_id_type',
          key: 'add_teacher.teacher_id_type',
          relationFields: ['teacher_id_number'],
          inputType: InputType.select,
          renderOption: ID_TYPE,
          required: true,
        },
        {
          label: '证件号码',
          name: 'add_teacher.teacher_id_number',
          key: 'add_teacher.teacher_id_number',
          relationFields: ['teacher_date_of_birth', 'teacher_gender'],
          required: true,
          ruleType: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type === 'resident_id_card') {
              return 'cnPeopleNo';
            }
            return '';
          },
          renderValidate: (formOjbectPanel: FormPanelObject) => {
            const id_type = formOjbectPanel.getFieldValue('teacher_id_type');
            if (id_type === 'resident_id_card') {
              return ExtendReader.validateCnPeopleNo(
                formOjbectPanel.getFieldValue('teacher_id_number'),
                formOjbectPanel.getFieldValue('teacher_date_of_birth'),
                formOjbectPanel.getFieldValue('teacher_gender')
              );
            }
            return '';
          },
        },
        {
          label: '性别',
          name: 'add_teacher.teacher_gender',
          key: 'add_teacher.teacher_gender',
          inputType: InputType.select,
          renderOption: GENDER,
          required: true,
          relationFields: ['teacher_id_number'],
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type !== 'resident_id_card') {
              return formObjectPanel.getFieldValue('teacher_gender');
            }
            return ExtendReader.renderGender('teacher_id_number', 'teacher_gender', formObjectPanel);
          },
        },
        {
          label: '出生年月',
          name: 'add_teacher.teacher_date_of_birth',
          key: 'add_teacher.teacher_date_of_birth',
          relationFields: ['teacher_id_number'],
          inputType: InputType.date,
          required: true,
          render: (formObjectPanel: FormPanelObject) => {
            const id_type = formObjectPanel.getFieldValue('teacher_id_type');
            if (id_type !== 'resident_id_card') {
              return formObjectPanel.getFieldValue('teacher_date_of_birth');
            }
            return ExtendReader.renderBirthday('teacher_id_number', 'teacher_date_of_birth', formObjectPanel);
          },
          formatSubmitValue: (value: any) => {
            if (value && value.isValid && value.isValid()) {
              return value.format('YYYY-MM-DD');
            }
            return value;
          },
        },
        {
          label: '教职工号',
          name: 'add_teacher.teacher_no', // todo：接口无教职工号
          key: 'add_teacher.teacher_no',
          required: true,
        },
      ],
    },
    {
      title: '调入校信息',
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      span: 12,
      inputs: [
        {
          label: '学校地区',
          name: 'transfer_details.current_district_area_id',
          key: 'transfer_details.current_district_area_id',
          //disabled: !nonSys,
          inputType: InputType.select,
          required: true,
          renderOption: country,
          relationFields: ['current_unit_id'],
        },
        {
          label: '单位名称',
          name: 'transfer_details.current_unit_id',
          key: 'transfer_details.current_unit_id',
          //disabled: !nonSys,
          required: true,
          inputType: InputType.search,
          renderOption: async (formPanelObject: FormPanelObject, searchTxt: string) =>
            searchSchoolByKeyOptions(formPanelObject, searchTxt, {
              school_id: formPanelObject.getFieldValue('current_unit_id'),
              block: formPanelObject.getFieldValue('area'),
            }),
          formatSubmitValue: val => {
            if (val && typeof val === 'object') {
              return val.value;
            }
            return val;
          },
        },
        {
          label: '任职岗位',
          name: 'transfer_details.current_position',
          key: 'transfer_details.current_position',
          inputType: InputType.cascader,
          required: true,
          renderOption: POSITION_TYPE, //TODO:类型无
          formatSubmitValue: (value: any) => {
            if (value && value.length && value.length > 0) {
              return value.join(',');
            }
            return value;
          },
        },
      ],
    },
    {
      title: '调出校信息',
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      span: 12,
      inputs: [
        {
          label: '调入区县',
          name: 'transfer_details.original_district',
          key: 'transfer_details.original_district',
          disabled: !nonSys,
          inputType: InputType.cascader,
          renderOption: getProvinceCityCascader,
        },
        {
          label: '单位名称',
          name: 'transfer_details.original_unit',
          key: 'transfer_details.original_unit',
          disabled: !nonSys,
        },
        {
          label: '调出日期',
          name: 'transfer_details.transfer_out_date',
          key: 'transfer_details.transfer_out_date',
          required: true,
          inputType: InputType.date,
          formatSubmitValue: (value: any) => {
            if (value && value.isValid && value.isValid()) {
              return value.format('YYYY-MM-DD');
            }
            return value;
          },
        },
        {
          label: '任职岗位',
          name: 'transfer_details.original_position',
          key: 'transfer_details.original_position',
          inputType: InputType.cascader,
          renderOption: POSITION_TYPE, //TODO:类型无
          formatSubmitValue: (value: any) => {
            if (value && value.length && value.length > 0) {
              return value.join(',');
            }
            return value;
          },
        },
        {
          label: '转出原因',
          name: 'transfer_details.transfer_reason',
          key: 'transfer_details.transfer_reason',
          required: true,
          inputType: InputType.textarea,
          span: 24,
          textRange: [0, 200],
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 22 },
          },
        },
        {
          label: '备注',
          name: 'transfer_details.remark',
          key: 'transfer_details.remark',
          inputType: InputType.textarea,
          span: 24,
          textRange: [0, 200],
          props: {
            labelCol: { span: 2 },
            wrapperCol: { span: 22 },
          },
        },
      ],
    },
  ];

  return (
    // <PageContainer header={<Breadcrumb items={[{ title: '人员信息调入' }]} />}>
    <>
      <FormPanel
        btnsAlign={FormPanelBtnAlign.right}
        restBtnText="重置"
        submitBtnText="查询"
        template={list}
        onReset={(formPanelObject: FormPanelObject) => {
          setNonSys(false);
          submitForm.resetFields();
          return true;
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          const res = await getTransferTeacher({ ...formPanelObject.getFieldsValue() });
          if (res.success && res.data) {
            const newdata = {};

            Object.keys(res.data).forEach(key => {
              newdata[`add_teacher.${key}`] = res.data[key];
            });
            setValues(newdata);
          } else {
            let id_info;
            if (formPanelObject.getFieldValue('teacher_id_type') === 'resident_id_card') {
              id_info = Utils.chineseIDCard(formPanelObject.getFieldValue('teacher_id_number'));
            }
            setValues(
              utils.flattenObject({
                add_teacher: {
                  teacher_date_of_birth: id_info.birth,
                  teacher_gender: id_info.gender === 1 ? GENDER[0].value : GENDER[1].value,
                  ...formPanelObject.getFieldsValue(),
                },
              })
            );
            setNonSys(true);
          }
        }}
      />

      {nonSys ? (
        <div style={{ color: 'red', position: 'absolute', top: '210px', left: '50px' }}>
          该教职工不在系统完善以下信息，继续调入流程
        </div>
      ) : (
        ''
      )}
      <FormPanel
        btnsAlign={FormPanelBtnAlign.center}
        buttonsDisplay={FormPanelBtnDisplay.block}
        restBtnText="取消"
        submitBtnText="提交"
        template={checkInfoList}
        values={values}
        onReset={() => {
          navigate(-1);
        }}
        onLoad={(formPanelObject: FormPanelObject) => {
          setSubmitForm(formPanelObject);
        }}
        onFinish={async (formPanelObject: FormPanelObject) => {
          console.log(formPanelObject.getFieldsValue());
          const params = formPanelObject.getFieldsValue();
          const createParams: TransferIn = utils.unflattenObject(params);

          // createParams.transfer_details.original_district_province_id = params.original_district[0];
          // createParams.transfer_details.original_district_city_id = params.original_district[1];
          // createParams.transfer_details.original_district_area_id = params.original_district[2];

          if (_.isArray(params['transfer_details.original_district'])) {
            createParams.transfer_details.original_district_province_id =
              params['transfer_details.original_district'][0];
            createParams.transfer_details.original_district_city_id = params['transfer_details.original_district'][1];
            createParams.transfer_details.original_district_area_id = params['transfer_details.original_district'][2];
          }

          // {
          //   transfer_details: {
          //     // 调入校信息
          //     current_district_area_id: params.current_district_area_id,
          //     current_unit_id: params.current_unit_id,
          //     current_position: params.current_position,
          //     // 调出校信息
          //     original_district_province_id: params.original_district[0],
          //     original_district_city_id: params.original_district[1],
          //     original_district_area_id: params.original_district[2],
          //     original_unit: params.original_unit,
          //     transfer_out_date: params.transfer_out_date,
          //     transfer_reason: params.transfer_reason,
          //     original_position: params.original_position,
          //     remark: params.params,
          //   },
          // };
          if (!nonSys) {
            delete createParams.add_teacher;
            createParams.transfer_details.teacher_id = values.teacher_id;
          }
          const res = await createTransferIn(createParams);
          if (res.success) {
            setNonSys(false);
            formPanelObject.resetFields();
            message.success('操作成功！');
          } else {
            formPanelObject.reVaildation(res);
          }
          return true;
        }}
      />
    </>
  );
};

export default Groups;
